<?php
/**
 * Router routing url request and compire uri to controller.
 * @package Core
 * @category Core
 * @author kovacsricsi
 */

class Router
{
	/**
	 * Read controller and parameters from Router class.
	 * @access public
	 * @static
	 * @return array
	 */
	public static function getController()
	{
		$uri = ($i = strpos($_SERVER['REQUEST_URI'],'?'))?substr($_SERVER['REQUEST_URI'], 0, $i):$_SERVER['REQUEST_URI'];

		$controller = array(
			'controller' => 'StaticController',
			'function'   => 'showPage',
			'params'     => array(
				'template' => '404'
			)
		);

		foreach(self::getUrls() as $url => $options) {
			$matches = array();

			if ( preg_match('!^' . $url . '$!', $uri, $matches) ) {
				$controller["controller"] = (isset($options['controller'])) ? $options['controller'] : null;
				$controller["function"]   = (isset($options['function'])) ? $options['function'] : null;
				$controller["parameter"]  = (isset($options['parameter'])) ? $options['parameter'] : null;

				if(isset($options['params'])) {
				     foreach($options['params'] as $var => $value) {
				          $_GET[$var] = $value;
				     }
				}

				if(isset($options['urlParams'])) {
					foreach($options['urlParams'] as $i => $var) {
						$_GET[$var] = $matches[$i+1];
					}
				}

				break;
			}
		}

		return $controller;
	}

	/**
	 * Parse urls, and create array.
	 * @access public
	 * @static
	 * @return array
	 */
	public static function getUrls()
	{
		eval('$urls = array(' . file_get_contents(DIR_CONFIG . '/urls.cfg') . ');');

		return $urls;
	}
}
?>